<template>
  <div class="roleList">
    <a-card :bordered="false" :style="{ height: '100%' }">
      <a-row :gutter="24">
        <a-col :md="4">
          <a-list itemLayout="vertical" :dataSource="roles">
            <a-list-item slot="renderItem" slot-scope="item, index" :key="index">
              <a-list-item-meta :style="{ marginBottom: '0' }">
                <span slot="description" style="text-align: center; display: block">{{ item.rlUniCode }}</span>
                <a slot="title" style="text-align: center; display: block" @click="edit(item)">{{ item.rlName }}</a>
              </a-list-item-meta>
            </a-list-item>
          </a-list>
        </a-col>
        <a-col :md="20">
          <div style="max-width: 800px">
            <a-divider v-if="isMobile()" />
            <div v-if="mdl.rlId">
              <h3>角色：{{ mdl.rlName }}</h3>
            </div>
            <a-form :form="form" :layout="isMobile() ? 'vertical' : 'horizontal'" @submit="handleSubmit">

              <a-form-item label="角色名称">
                <a-input v-decorator="[ 'rlName', {rules: [{ required: true, message: '请填写角色名称!' }]} ]" placeholder="请填写角色名称" />
              </a-form-item>

              <a-form-item label="唯一键">
                <a-input v-decorator="[ 'rlUniCode', {rules: [{ required: true, message: '请填写唯一键!' }]} ]" placeholder="请填写唯一键" />
              </a-form-item>

              <a-form-item label="拥有权限">
                <a-row :gutter="24">
                  <a-col
                    style=" display: flex;justify-content: flex-start;align-items: center;"
                    :lg="24"
                    :md="24"
                    :sm="24">
                    <div>
                      <div v-for="item in loadData" :key="item.permsId">
                        <a-checkbox :indeterminate="item.indeterminate" :checked="item.checkedAll" @change="onChangeCheckAll($event, item,item.permsId)" >全选</a-checkbox>
                        <a-checkbox-group style="margin-left:20px" v-model="item.selected" @change="onChangeCheck($event,item)" >
                          <a-checkbox v-for="child in item.actionsOptions" :key="child.permsId" @change="clickChenck($event, item)" :value="child.uniCode">{{ child.permsName }}</a-checkbox>
                        </a-checkbox-group>
                      </div>
                    </div>
                  </a-col>
                </a-row>
              </a-form-item>
              <a-form-item >
                <div v-if="mdl.rlId==='-1'|| mdl.rlId===undefined">
                  <a-button type="primary" html-type="submit">提交</a-button>
                </div>
                <div v-else>
                  <a-button type="primary" @click="doEdit">保存</a-button>
                  <a-popconfirm placement="top" okText="确定" cancelText="取消" @confirm="delRole(mdl.rlId)">
                    <template slot="title">
                      确认删除吗?
                    </template>
                    <a-button style="margin-left:20px" type="danger" >删除</a-button>
                  </a-popconfirm>
                </div>
              </a-form-item>
            </a-form>
          </div>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script>
import { getRoleList, doAddRole, getPermsList, doEditRole, delRole } from '@/api/admin/permission'
// import { getRoleList } from '@/api/local/permission'
import { mixinDevice } from '@/utils/mixin'
// import { actionToObject } from '@/utils/permissions'
import pick from 'lodash.pick'

export default {
  name: 'RoleList',
  mixins: [mixinDevice],
  components: {},
  data () {
    return {
      checkedList: [],
      indeterminate: true,
      checkAll: false,
      plainOptions: [],
      form: this.$form.createForm(this),
      mdl: {},
      loadData: [],
      roles: [
        {
          rlId: '-1',
          rlName: '新增角色',
          rlUniCode: '新增一个角色'
        }
      ],
      valuses: {},
      // permisNameList: [],
      chList: [],
      permischeck: [],
      a: [],
      b: [],
      tem: [],
      checkedRole: [],
      c: [],
      d: []
    }
  },
  created () {
    this.getPermsList()
  },
  methods: {
    clickChenck (e, item) {
      event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true
      // console.log('e.target.value', e.target.value)
      // console.log('item', item)
      // 选中
      if (e.target.checked === true) {
        // console.log('选中')
        if (this.checkedList.includes(e.target.value)) {
        } else {
          this.checkedList.push(e.target.value)
        }
      }
      // 取消选中
      if (e.target.checked === false) {
        // console.log('取消选中')
        this.checkedList.splice(this.checkedList.indexOf(e.target.value), 1)
      }
      // console.log('this.checkedList', this.checkedList)
    },
    onChangeCheck (e, item) {
      item.indeterminate = !!item.selected.length && (item.selected.length < item.actionsOptions.length)
      // console.log('item.indeterminate', item.indeterminate)
      item.checkedAll = item.selected.length === item.actionsOptions.length
    },
    onChangeCheckAll (e, item, id) {
      // console.log(id)
      Object.assign(item, {
        selected: e.target.checked ? item.actionsOptions.map(obj => obj.uniCode) : [],
        indeterminate: false,
        checkedAll: e.target.checked
      })
      // console.log(e.target.checked)
      this.tem.push(...item.selected)
      // console.log('this.tem', this.tem)
      // 取消选中
      if (e.target.checked === false) {
        this.checkFalse(id)
      }
      // 全选中
      if (e.target.checked === true) {
        for (let h = 0; h < this.tem.length; h++) {
          // console.log('点击')
          if (this.checkedList.indexOf(this.tem[h]) !== -1) {
          } else {
            this.checkedList.push(this.tem[h])
          }
        }
      }
      this.tem = []
      // console.log('this.checkedList', this.checkedList)
    },
    checkFalse (id) {
      const obj = this.loadData.filter(e => e.permsId === id)
      // console.log('obj', obj)
      this.obj1 = obj[0].actions
      // console.log(this.obj1)
      this.obj1.forEach((item, index, array) => {
        this.checkedList.splice(this.checkedList.indexOf(item), 1)
      })
      this.tem = []
      // console.log('取消点击')
    },
    doEdit () {
      // this.values.rlName = this.form.rlId
      this.form.validateFields((err, values) => {
        if (!err) {
          values.rlId = this.mdl.rlId
          values.rlPermsList = this.checkedList
          this.valuses = values
          this.doEditRole(values)
          // console.log('form: ', values)
          // console.log('this.values', this.values)
        }
      })
    },
    doEditRole (values) {
      doEditRole(
        {
          rlId: values.rlId,
          rlName: values.rlName,
          rlUniCode: values.rlUniCode,
          rlPermsList: JSON.stringify(values.rlPermsList)
        }
      ).then((res) => {
        // console.log(res)
        this.$message.success('修改成功!')
        this.getPermsList()
        this.form = this.$form.createForm(this)
        this.checkedList = []
        this.mdl.rlName = ''
      }).catch(err => {
        this.$message.error('修改失败!')
        console.log(err)
      })
    },
    delRole (id) {
      delRole({
        rlId: id
      }).then((res) => {
        // console.log(res)
        this.$message.success('删除成功!')
        this.getPermsList()
        this.form = this.$form.createForm(this)
        this.checkedList = []
        this.mdl.rlName = ''
      }).catch(err => {
        console.log(err)
        this.$message.error('删除失败!')
      })
    },
    getRoleList () {
      this.roles = [{
        rlId: '-1',
        rlName: '新增角色',
        rlUniCode: '新增一个角色',
        rlPermsList: []
      }]
      getRoleList().then((res) => {
        this.roles.push(...res.result.role)
        // this.roles = res.result
        const temp = this.roles.map(function (obj) {
          var rObj = {}
          rObj.rlId = obj.rlId
          rObj.rlName = obj.rlName
          rObj.rlUniCode = obj.rlUniCode
          rObj.rlPermsList = obj.rlPermsList
          rObj.loadData = []
          return rObj
        })
        // console.log('temp', temp)
        for (var r = 0; r < temp.length; r++) {
          temp[r].loadData.push(...this.loadData)
        }
        this.roles = temp
        // console.log('this.roles', this.roles)
      }).catch(err => {
        console.log(err)
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          values.rlPermsList = this.checkedList
          this.valuses = values
          // console.log('form: ', values)
          this.doAddRole(values)
        }
      })
    },

    getPermsList () {
      getPermsList().then(res => {
        // console.log('权限列表', res.result.role)
        this.loadData = []
        this.a = []
        this.b = []
        for (const i in res.result.role) {
          this.loadData.push(res.result.role[i])
        }
        const arr1 = [].slice.call(this.loadData)
        // console.log('arr1', arr1)
        // 增加需要的新属性
        this.a = arr1.map(function (obj) {
          var rObj = {}
          rObj.permsId = obj.permsId
          rObj.uniCode = obj.uniCode
          rObj.permsName = obj.permsName
          rObj.parentUniCode = obj.parentUniCode
          rObj.children = obj.children
          rObj.indeterminate = false
          rObj.checkedA11 = false
          rObj.selected = []
          rObj.actions = []
          rObj.actionsOptions = []
          return rObj
        })
        // 新属性赋值
        for (var c = 0; c < arr1.length; c++) {
          this.b = []
          this.b.push(arr1[c])
          if (arr1[c].children) {
            this.b.push(...arr1[c].children)
          }
          this.a[c].actionsOptions = this.b
          this.c.push(this.b)
        }
        const arr2 = [].slice.call(this.c)
        for (let f = 0; f < arr2.length; f++) {
          const temp = []
          for (let d = 0; d < arr2[f].length; d++) {
            temp.push(arr2[f][d].uniCode)
          }
          if (this.a[f] !== undefined) {
            this.a[f].actions = [].slice.call(temp)
          }
          // this.d.push([].slice.call(temp))
        }
        // const arr3 = [].slice.call(this.d)
        // console.log('arr3', arr3)
        this.loadData = [].slice.call(this.a)
        // console.log('loadData111', this.loadData)
        this.getRoleList()
      }).catch(err => {
        console.log(err)
        this.loading = false
      })
    },
    doAddRole (value) {
      console.log('value', value)
      doAddRole({
        rlName: value.rlName,
        rlUniCode: value.rlUniCode,
        rlPermsList: JSON.stringify(value.rlPermsList)
      }
      ).then(res => {
        console.log(res)
        this.$message.success('添加成功!')
        this.getRoleList()
        this.getPermsList()
        this.form = this.$form.createForm(this)
        this.checkedList = []
        this.mdl.rlName = ''
      }).catch(err => {
        console.log(err)
        this.$message.error('添加失败!')
      })
    },
    eval (fn) {
      // 数组字符串转数组
      var Fn = Function // 一个变量指向Function，防止有些前端编译工具报错
      return new Fn('return ' + fn)()
    },
    edit (record) {
      this.mdl = Object.assign({}, record)
      for (let c = 0; c < record.loadData.length; c++) {
        record.loadData[c].selected = []
        record.loadData[c].checkedAll = false
        record.loadData[c].indeterminate = false
      }
      if (record.rlId === '-1') {
        this.form = this.$form.createForm(this)
        this.checkedList = []
      } else {
        var arrtep = []
        arrtep = this.eval(record.rlPermsList)
        console.log('record', record)
        arrtep.forEach((item, index, array) => {
          for (let a = 0; a < record.loadData.length; a++) {
            if (record.loadData[a].actions.includes(item)) {
              record.loadData[a].selected.push(item)
            }
            // }
            if (record.loadData[a].selected.length === 0) {
              record.loadData[a].checkedAll = false
              record.loadData[a].indeterminate = false
            } else if (record.loadData[a].selected.length < record.loadData[a].actions.length) {
              record.loadData[a].checkedAll = false
              record.loadData[a].indeterminate = true
            } else if (record.loadData[a].selected.length === record.loadData[a].actions.length) {
              record.loadData[a].checkedAll = true
              record.loadData[a].indeterminate = false
            }
          }
        })
        console.log('this.loadData', this.loadData)
        // this.rlPermsList = eval('(' + record.rlPermsList + ')')
        this.rlPermsList = this.eval(record.rlPermsList)
        this.checkedList = this.rlPermsList
        console.log('this.checkedList', this.checkedList)
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.mdl, 'rlUniCode', 'rlName'))
        })
      }
      // console.log('this.mdl', this.mdl)
    }
  }
}
</script>

<style scoped>

</style>
